#include "AccountServer.h"
#include "JME_Core.h"
#include "JME_JsonFile.h"
#include "JME_RpcHandler.h"
#include "AccountHandler.h"
#include "DispatchHandler.h"

void AccountServer::init()
{
	{
		auto& dbConf = _config["mysql"];
		_mysqlDBPool = MysqlDBPool::create(4, boost::bind(connectMysql, _1, dbConf["addr"].asString(), dbConf["username"].asString(), dbConf["passwd"].asString(), dbConf["dbname"].asString(), dbConf["port"].asInt()));
	}
	{
		auto& dbConf = _config["mongo"];
		_mongoDBPool = MongoDBPool::create(4, boost::bind(connectMongoDB, _1, dbConf["addr"].asString(), dbConf["dbname"].asString(), dbConf["username"].asString(), dbConf["passwd"].asString()));
	}

	DispatchHandler::init();

	JME_RpcHandler::bindHandler<AccountRpcHandler>();
}

AccountServer::AccountServer()
{
	
}

AccountServer::AccountServerPtr AccountServer::getInstance()
{
	static AccountServerPtr _pInstance = AccountServerPtr(new AccountServer);
	return _pInstance;
}


MysqlDBPool* AccountServer::getMysqlDBPool()
{
	return _mysqlDBPool.get();
}

AccountServer::~AccountServer()
{

}

MongoDBPool* AccountServer::getMongoDBPool()
{
	return _mongoDBPool.get();
}


bool connectMongoDB(JME_MongoConnection* conn, const string& ip_str, const string& db_name, const string& name, const string& pwd)
{
	std::string errorStr;
	if(!conn->connect(ip_str, &errorStr))
	{
		LOGE("Connect to mongodb server [ %s ] failed", ip_str);
		return false;
	}
	if ( !conn->auth(db_name, name , pwd, &errorStr) )
	{
		LOGE("Try to auth with [ %s : %s : %s ] failed", name, pwd, db_name);
		return false;
	}
	return true;
}

bool connectMysql(MysqlConnector* conn, const string& ip, const string& userName, const string& pwd, const string& dbName, const unsigned short port)
{
	conn->setConfig(ip, userName, pwd, dbName, port);
	return conn->connect();
}
